package com.cande.loki.exercise.nettytest;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class NettyServer {
    public static void main(String[] args) throws Exception {
        //创建两个线程组 bossgroup 和workergroup
        EventLoopGroup group = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //创建服务端的启动对象 设置参数
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(group, workerGroup)
                    //设置服务端通道实现类型
                    .channel(NioServerSocketChannel.class)
                    //设置线程队列得到的连接个数
                    .option(ChannelOption.SO_BACKLOG,128)
                    .childOption(ChannelOption.SO_KEEPALIVE,true)
                    //设置地址端口
                    .localAddress(new InetSocketAddress(9999))
                    //使用匿名内部类的形式初始化通道对象
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //给管道设置处理器
                            socketChannel.pipeline().addLast(new ServerHandler());
                        }
                    });
            //绑定端口 启动服务
            ChannelFuture sync = bootstrap.bind().sync();
            System.out.println(NettyServer.class.getName() + " started and listen on " + sync.channel().localAddress());
            //对关闭通道进行监听
            sync.channel().closeFuture().sync();
        }catch (Exception e){

        }finally {
            group.shutdownGracefully().sync();
            workerGroup.shutdownGracefully().sync();
        }
    }
}
